package models

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"itachi/pkg/setting"
	"log"
)

var db *gorm.DB

type Model struct {
	ID         int `grom:"primary_key" json:"id"`
	CreatedOn  int `json:"create_on"`
	ModifiedOn int `json:"modified_on"`
}

func init() {
	var (
		Type, User, Password, Host, Name, TablePrefix string
	)
	sec, err := setting.Cfg.GetSection("database")
	if err != nil {
		log.Fatalf("Fail to get section 'database': %v", err)
	}
	Type = sec.Key("Type").String()
	User = sec.Key("User").String()
	Password = sec.Key("Password").String()
	Host = sec.Key("Host").String()
	Name = sec.Key("Name").String()
	TablePrefix = sec.Key("TablePrefix").String()

	str := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", User, Password, Host, Name)
	db, err = gorm.Open(Type, str)

	if err != nil {
		log.Fatal(err)
	}
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return TablePrefix + defaultTableName
	}
	db.SingularTable(true)
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
}

func CloseDb() {
	defer db.DB().Close()
}
